<template>
    <div class="basic-info">
        <h3 class="page-title">联保小组信息</h3>
        <form class="form">
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-number">联保小组编号:</label>
                    <input type="text" id="loan-application-id" v-model="groupInfo.id" class="form-control" />
                </div>
                <div class="form-group">
                    <label for="loan-application-name">联保小组名称:</label>
                    <input type="text" id="loan-application-name" v-model="groupInfo.name" class="form-control" />
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-type">保证方式:</label>
                    <select id="loan-application-type" v-model="groupInfo.ensureMethod" class="form-control">
                        <option value="连带责任保证">连带责任保证</option>
                        <option value="一般保证">一般保证</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="leader-customer-number">联保组长客户号:</label>
                    <div class="input-with-button">
                        <input type="text" id="leader-customer-number" v-model="groupInfo.leaderCustomerNumber"
                            class="form-control" />
                        <el-button type="primary" @click="showCustomerDialog">选择客户</el-button>
                    </div>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="leader-customer-name">联保组长客户名称:</label>
                    <input type="text" id="leader-customer-name" v-model="groupInfo.leaderCustomerName"
                        class="form-control" />
                </div>
                <div class="form-group">
                    <label for="loan-application-member_number">联保成员数量:</label>
                    <input type="text" id="loan-application-member_number" v-model="groupInfo.memberNumber"
                        @blur="checkMemberNumber" class="form-control" />
                </div>
            </div>

            <h3 class="page-title">联保小组额度信息</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-number">联保小组总额度（元）:</label>
                    <input type="text" id="loan-application-sum_price" v-model="groupInfo.sumPrice"
                        class="form-control" />
                </div>
                <div class="form-group">
                    <label for="loan-application-name">币种</label>
                    <input type="text" id="loan-application-currency" v-model="groupInfo.currency"
                        class="form-control" />
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-deposit">是否收取保证金</label>
                    <select id="loan-application-deposit" v-model="groupInfo.deposit" @change="onDepositChange"
                        class="form-control">
                        <option value="0">否</option>
                        <option value="1">是</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="loan-application-name">保证金总额度(元)</label>
                    <input type="text" id="loan-application-deposit_amount"
                        :value="groupInfo.deposit === 0 ? 0 : groupInfo.depositAmount"
                        :disabled="groupInfo.deposit === 0" @input="updateDepositAmount" class="form-control" />
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-start-date">联保起始日期:</label>
                    <input type="date" id="loan-application-start-date" v-model="groupInfo.insuranceStartTime"
                        class="form-control" />
                </div>
                <div class="form-group">
                    <label for="loan-application-end-date">联保到期日期:</label>
                    <input type="date" id="loan-application-end-date" v-model="groupInfo.insuranceEndTime"
                        class="form-control" />
                </div>
            </div>
            <h3 class="page-title">登记信息</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-number">客户经理:</label>
                    <input type="text" id="loan-application-userId" v-model="displayedUserId" class="form-control"
                        :readonly="true" />
                </div>
                <div class="form-group">
                    <label for="loan-application-name">网点</label>
                    <input type="text" id="loan-application-currency" v-model="groupInfo.branch" class="form-control" />
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="loan-application-start-date">登记日期:</label>
                    <input type="date" id="loan-application-create_time-date" v-model="groupInfo.createTime"
                        class="form-control" />
                </div>
                <div class="form-group">
                    <label for="loan-application-status">审批状态</label>
                    <select id="loan-application-status" v-model="groupInfo.status" class="form-control">
                        <option v-for="(option, index) in statusOptions" :key="index" :value="option.value">{{
                        option.text }}</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <el-button type="success" @click="submit">提交</el-button>
                    <el-button type="danger" @click="goBack">返回</el-button>
                </div>
            </div>
        </form>
        <!-- 客户选择对话框 -->
        <el-dialog :visible.sync="customerDialogVisible" title="选择客户" width="50%">
            <!-- 客户列表 -->
            <div class="customer-list">
                <el-checkbox-group v-model="selectedCustomers">
                    <el-checkbox v-for="customer in customers" :key="customer.id" :label="customer.id">
                        {{ customer.name }} - {{ customer.id }}
                    </el-checkbox>
                </el-checkbox-group>
            </div>
            <!-- 确定和取消按钮 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="customerDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmCustomer">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'BasicInfo',
    data() {
        return {
            depositAmount: 0,
            originalDepositAmount: 0, // 新增：用于保存原来的保证金金额
            userId: "",
            displayedUserId: '',
            groupInfo: {

            },
            customerDialogVisible: false,
            customers: [],
            selectedCustomers: [],
            statusOptions: [
                { value: 0, text: '待审核' },
                { value: 1, text: '审核通过' },
                { value: 2, text: '已退回' },
            ],
        };
    },
    methods: {
        onDepositChange(event) {
            this.groupInfo.deposit = Number(event.target.value);
        },
        updateDepositAmount(event) {
            if (!this.groupInfo.deposit) return;
            this.groupInfo.depositAmount = event.target.value;
        },

        checkMemberNumber() {
            const number = parseInt(this.groupInfo.memberNumber);
            if (isNaN(number) || number < 3 || number > 5) {
                alert('联保成员数量必须在3到5之间');
                // 清空输入框
                this.groupInfo.memberNumber = '';
            }
        },
        showCustomerDialog() {
            this.axios
                .post("api/customer-server/queryAllCustomers")
                .then((res) => {
                    this.customers = res.data.data;
                    this.customerDialogVisible = true;
                })
                .catch((error) => {
                    console.error("Error fetching customer list:", error);
                });
        },
        confirmCustomer() {
            const selectedIds = this.selectedCustomers;
            const selectedCustomers = this.customers.filter(customer => selectedIds.includes(customer.id));
            if (selectedCustomers.length > 0) {
                const selectedCustomer = selectedCustomers[0];
                this.groupInfo.leaderCustomerNumber = selectedCustomer.id;
                this.groupInfo.leaderCustomerName = selectedCustomer.name;
            }
            this.customerDialogVisible = false;
        },
        submit() {
            let insuranceTeam = {
                id: this.groupInfo.id,
                name: this.groupInfo.name,
                ensureMethod: this.groupInfo.ensureMethod,
                leaderCustomerNumber: this.groupInfo.ileaderCustomerNumber,
                leaderCustomerName: this.groupInfo.leaderCustomerName,
                memberNumber: this.groupInfo.memberNumber,
                currency: this.groupInfo.currency,
                deposit: this.groupInfo.deposit,
                depositAmount: this.groupInfo.depositAmount,
                sumPrice: this.groupInfo.sumPrice,
                insuranceStartTime: this.groupInfo.insuranceStartTime,
                insuranceEndTime: this.groupInfo.insuranceEndTime,
                userId: this.displayedUserId,
                status: this.groupInfo.status,
                createTime: this.groupInfo.createTime,
            }

            this.axios.post("api/customer-server/addGroup", insuranceTeam).then(res => {
                console.log(res.data)
                if (res.data.code == 200) {

                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });

                    this.$router.push("/limitApplication");
                }

                if (res.data.code == 1002) {
                    this.$message.error(res.data.data);
                }

            })
        },
        goBack() {

            this.$router.push("/limitApplication");
        },


    },
    created() {
        const token = localStorage.getItem("JWToken");
        if (!token) {
            return;
        }
        const parts = token.split(".");
        const payload = JSON.parse(atob(parts[1]));
        this.userId = payload.id;
        this.displayedUserId = this.userId;
        console.log(this.userId);


        this.originalDepositAmount = this.groupInfo.depositAmount;
    },

};
</script>

<style scoped>
.disabled {
    background-color: #eee;
    cursor: not-allowed;
}

.basic-info {
    padding: 20px;
}

.page-title {
    font-size: 24px;
    margin-bottom: 20px;
}

.form {
    max-width: 800px;
    /* 调整表单容器的最大宽度 */
}

.form-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    /* 调整每一行之间的间距 */
}

.form-group {
    flex: 1;
    margin-right: 10px;
    /* 调整每个表单组件之间的间距 */
}

.form-group:last-child {
    margin-right: 0;
}

.label {
    display: inline-block;
    width: 150px;
    font-weight: bold;
}

.form-control {
    width: 100%;
    /* 调整表单控件的宽度 */
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

/* Flexbox 布局用于带按钮的输入框 */
.input-with-button {
    display: flex;
    align-items: center;
}

.input-with-button input {
    flex: 1;
    margin-right: 10px;
    /* 调整输入框和按钮之间的间距 */
}
</style>
